package spitfire;

import light3d.*;

import java.awt.*;

public class SpitfireBufferedCanvas extends EngineWindow
{
	PointWithAngle camera;
	final static int w = 640, h = 480;
	final double INFINITY = 10000;
	final int SPECK_COUNT = 100;
	BasicMesh specks = new BasicMesh();
	
	public SpitfireBufferedCanvas()
	{
		super("Spitfire", w, h);
		
		final double SPECK_RADIUS = 1;
		final double fieldWidth = 100, fieldLength = 150;
		for (int i = 0; i < SPECK_COUNT; i++)
		{
			Point3D a = new Point3D(0,0,SPECK_RADIUS),
					b = new Point3D(-SPECK_RADIUS, 0, SPECK_RADIUS),
					c = new Point3D(SPECK_RADIUS, 0, SPECK_RADIUS);
			
			a.finalizeCoordinates();
			b.finalizeCoordinates();
			c.finalizeCoordinates();
			
			int cR = (int)(Math.random()*100 + 155),
				cG = (int)(cR - Math.random()*cR/2),
				cB = (int)(cG - Math.random()*cG/2);
			
			Triangle speck = new Triangle(getRGBColor(cR,cG,cB), a, b, c);
			speck.rotate(0, Math.random()*360, 0);
			speck.translate(fieldWidth*Math.random() - fieldWidth/2, 0, fieldLength*Math.random() - fieldLength/2);
			speck.finalizeCoordinates();
			specks.appendTriangle(speck);
		}
		specks.finalizeMesh();
	}
	public void setCameraLocation(PointWithAngle currentLocation)
	{
		camera = currentLocation;
	}
	public void perform2DOperations(Graphics2D graphics2d)
	{
		graphics2d.setColor(Color.BLUE);
		graphics2d.fillRect(0, 0, bufferWidth, bufferHeight);
		
		
		int y = (int)(FastMath.sin(camera.getRX())*INFINITY/INFINITY * h + h/2);
		
		if (y > h)
		{
			return;
		}
		double xArea = FastMath.tan(camera.getRX());
		
		int leftY = (int)((FastMath.sin(camera.getRX())*INFINITY/INFINITY) * h);
		int rightY = (int)((FastMath.sin(camera.getRX())*INFINITY/INFINITY) * h);
		
		int ly = h;
		
		
		int ang = (int)FastMath.validateAngle(camera.getRX());
		
		double angleAdd = 0;
		if (ang > 90 && ang < 270)
		{
			angleAdd = 180;
		}
		
		int lowY = (int)FastMath.constrain(ly, 0, h);
		
		
		Point3D[] p = new Point3D[4];
		
		p[0] = new Point3D(-w, leftY, 0);
		p[1] = new Point3D(w, rightY, 0);
		p[2] = new Point3D(w, lowY, 0);
		p[3] = new Point3D(-w, lowY, 0);
		
		int[] pointX = new int[4];
		int[] pointY = new int[4];
		for (int i = 0; i < 4; i++)
		{
			p[i].rotate(0, 0, camera.getRZ() + angleAdd);
			p[i].translate(w/2, h/2, 0);
			pointX[i] = (int)p[i].getX();
			pointY[i] = (int)p[i].getY();
		}

		graphics2d.setColor(Color.ORANGE);
		graphics2d.fillPolygon(pointX, pointY, 4);
	}
  public double endRender(BufferedCanvas bufferedCanvas, PointWithAngle camera)
  {
		specks.render(bufferedCanvas, camera);
		return endRender();
  }
}
